package main.api;

import main.RequestHelper;
import main.ResponseHelper;
import main.database.MessageHelper;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class MessageApi {
    @PostMapping("/api/sendmessage")
    public ResponseEntity<?> sendMessage(HttpServletRequest request) {
        String uuid = RequestHelper.getUserUUIDFromRequest(request);

        String toUser = null, message = null, fromUser = null;
        Map<String, String[]> map = request.getParameterMap();
        if (map.containsKey("to")) {
            toUser = map.get("to")[0];
        }
        if (map.containsKey("message")) {
            message = map.get("message")[0];
        }
        if (map.containsKey("from")) {
            fromUser = map.get("from")[0];
        }

        String result;
        if (uuid == null || uuid.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "必须登录后才能发送消息").toString();
        }
        else if (fromUser == null || fromUser.isEmpty() || toUser == null || toUser.isEmpty() || message == null || message.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "参数不正确，必须还有from, to和message").toString();
        }
        else {
            MessageHelper.addMessage(fromUser, toUser, message);
            result = ResponseHelper.createBasicJsonObject(200, "ok").toString();
        }

        return ResponseEntity.ok(result);
    }
}
